package com.xiyi.shouxin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.xiyi.shouxin.controller.pojo.ListAdminParams;
import com.xiyi.shouxin.controller.pojo.LoginParams;
import com.xiyi.shouxin.controller.pojo.MenuParams;
import com.xiyi.shouxin.entity.admin.Admin;
import com.xiyi.shouxin.exception.ErrorCode;
import com.xiyi.shouxin.init.CacheUtil;
import com.xiyi.shouxin.init.DelayTask;
import com.xiyi.shouxin.service.AdminService;
import com.xiyi.shouxin.utils.ExceptionUtil;
import com.xiyi.shouxin.view.CommonModel;
import com.xiyi.shouxin.view.pojo.AdminView;
import com.xiyi.shouxin.view.pojo.ItemPage;
import com.xiyi.shouxin.view.pojo.MenuView;
import com.xiyi.shouxin.view.pojo.RoleView;

@CrossOrigin("*")
@RequestMapping("/admin")
@RestController
public class AdminController {
    private Gson gson = new Gson();
    @Autowired
    private Logger logger;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private AdminService adminService;

    @PostMapping("/login")
    public CommonModel login(@RequestBody LoginParams params) {
        if (params == null) {
            return CommonModel.Fail(ErrorCode.INVALIDPARAMTER.getCode(), ErrorCode.INVALIDPARAMTER.getMsg(), null);
        }
        try {
            AdminView admin = adminService.login(params.getAccount(), params.getPassword());
            String token = adminService.generateTokenForAdmin(admin);
            cacheUtil.putTokenAdmin(token, admin);
            cacheUtil.offerDelayTask(new DelayTask(token, 7 * 24 * 3600 * 1000));
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("info", admin);
            return CommonModel.Success(data);
        } catch (Exception e) {
            logger.error("{}登陆{}异常：", gson.toJson(cacheUtil.getAdminOperator()), gson.toJson(params), e);
            return ExceptionUtil.GetCommonModel(e);
        }
    }




    @PostMapping("/get_menus")
    public CommonModel getMenus() {
        if (cacheUtil.getAdminOperator()==null) {
            return CommonModel.Fail(ErrorCode.NOLOGIN.getCode(), ErrorCode.NOLOGIN.getMsg(), null);
        }
        try {
            List<MenuView> info = adminService.findAllMenuByAdmin(cacheUtil.getAdminOperator().getId());
            return CommonModel.Success(info);
        } catch (Exception e) {
            logger.error("{}获取菜单异常：", gson.toJson(cacheUtil.getAdminOperator()), e);
            return ExceptionUtil.GetCommonModel(e);
        }
    }

    @PostMapping("/list_admin")
    public CommonModel listAdmin(@RequestBody ListAdminParams params) {
        if (params == null || params.getPage() == null || params.getSize() == null) {
            return CommonModel.Fail(ErrorCode.INVALIDPARAMTER.getCode(), ErrorCode.INVALIDPARAMTER.getMsg(), null);
        }
        try {
            ItemPage<AdminView> info = adminService.findAdminList(cacheUtil.getAdminOperator(), params.getKeyword(),
                    params.getPage(),
                    params.getSize());
            return CommonModel.Success(info);
        } catch (Exception e) {
            logger.error("{}查询管理员列表{}异常：", gson.toJson(cacheUtil.getAdminOperator()), gson.toJson(params), e);
            return ExceptionUtil.GetCommonModel(e);
        }
    }

    @PostMapping("/create_admin")
    public CommonModel createAdmin(@RequestBody Admin params) {
        if (params == null) {
            return CommonModel.Fail(ErrorCode.INVALIDPARAMTER.getCode(), ErrorCode.INVALIDPARAMTER.getMsg(), null);
        }
        try {
            AdminView info = adminService.createAdmin(cacheUtil.getAdminOperator(), params);
            return CommonModel.Success(info);
        } catch (Exception e) {
            logger.error("{}新增管理员{}异常：", gson.toJson(cacheUtil.getAdminOperator()), gson.toJson(params), e);
            return ExceptionUtil.GetCommonModel(e);
        }
    }

    @PostMapping("/update_admin")
    public CommonModel updateAdmin(@RequestBody Admin params) {
        if (params == null || params.getId() == null) {
            return CommonModel.Fail(ErrorCode.INVALIDPARAMTER.getCode(), ErrorCode.INVALIDPARAMTER.getMsg(), null);
        }
        try {
            adminService.updateAdmin(cacheUtil.getAdminOperator(), params);
            return CommonModel.Success(null);
        } catch (Exception e) {
            logger.error("{}修改管理员{}异常：", gson.toJson(cacheUtil.getAdminOperator()), gson.toJson(params), e);
            return ExceptionUtil.GetCommonModel(e);
        }
    }

    @PostMapping("/disable_admin")
    public CommonModel disableAdmin(@RequestBody Admin params) {
        if (params == null || params.getId() == null) {
            return CommonModel.Fail(ErrorCode.INVALIDPARAMTER.getCode(), ErrorCode.INVALIDPARAMTER.getMsg(), null);
        }
        try {
            adminService.disableAdmin(cacheUtil.getAdminOperator(), params.getId(),
                    params.getIsDelete() == null ? true : "0".equals(params.getIsDelete()));
            return CommonModel.Success(null);
        } catch (Exception e) {
            logger.error("{}禁用/启用管理员{}异常：", gson.toJson(cacheUtil.getAdminOperator()), gson.toJson(params), e);
            return ExceptionUtil.GetCommonModel(e);
        }
    }

    @PostMapping("/del_admin")
    public CommonModel delAdmin(@RequestBody List<Long> ids) {
        try {
            adminService.delAdmins(cacheUtil.getAdminOperator(), ids);
            return CommonModel.Success(null);
        } catch (Exception e) {
            logger.error("{}删除管理员{}异常：", gson.toJson(cacheUtil.getAdminOperator()), gson.toJson(ids), e);
            return ExceptionUtil.GetCommonModel(e);
        }
    }

    @PostMapping("/info_admin")
    public CommonModel infoAdmin(@RequestBody Admin params) {
        if (params == null || params.getId() == null) {
            return CommonModel.Fail(ErrorCode.INVALIDPARAMTER.getCode(), ErrorCode.INVALIDPARAMTER.getMsg(), null);
        }
        try {
            AdminView info = adminService.findAdmin(cacheUtil.getAdminOperator(), params.getId());
            return CommonModel.Success(info);
        } catch (Exception e) {
            logger.error("{}查询管理员详情{}异常：", gson.toJson(cacheUtil.getAdminOperator()), gson.toJson(params), e);
            return ExceptionUtil.GetCommonModel(e);
        }
    }

    @PostMapping("/list_role")
    public CommonModel listRole() {
        try {
            ItemPage<RoleView> info = adminService.findRoleList(null, 1, 100);
            return CommonModel.Success(info);
        } catch (Exception e) {
            logger.error("查询角色列表异常：", e);
            return ExceptionUtil.GetCommonModel(e);
        }
    }

    @PostMapping("/list_menu")
    public CommonModel listMenu() {
        try {
            List<MenuView> info = adminService.findAllMenu();
            return CommonModel.Success(info);
        } catch (Exception e) {
            logger.error("查询菜单列表异常：", e);
            return ExceptionUtil.GetCommonModel(e);
        }
    }

    @PostMapping("/create_menu")
    public CommonModel createMenu(@RequestBody MenuParams params) {
        if (params == null || params.getName() == null || params.getMenuType() == null) {
            return CommonModel.Fail(ErrorCode.INVALIDPARAMTER.getCode(), ErrorCode.INVALIDPARAMTER.getMsg(), null);
        }
        try {
            params.setId(null);
            MenuView info = adminService.createMenu(cacheUtil.getAdminOperator(), params.toMenu(), params.getRoleIds());
            return CommonModel.Success(info);
        } catch (Exception e) {
            logger.error("{}添加菜单{}异常：", gson.toJson(cacheUtil.getAdminOperator()), gson.toJson(params), e);
            return ExceptionUtil.GetCommonModel(e);
        }
    }

    @PostMapping("/update_menu")
    public CommonModel updateMenu(@RequestBody MenuParams params) {
        if (params == null || params.getId() == null) {
            return CommonModel.Fail(ErrorCode.INVALIDPARAMTER.getCode(), ErrorCode.INVALIDPARAMTER.getMsg(), null);
        }
        try {
            adminService.updateMenu(cacheUtil.getAdminOperator(), params.toMenu(), params.getRoleIds());
            return CommonModel.Success(null);
        } catch (Exception e) {
            logger.error("{}更新菜单{}异常：", gson.toJson(cacheUtil.getAdminOperator()), gson.toJson(params), e);
            return ExceptionUtil.GetCommonModel(e);
        }
    }

    @PostMapping("/del_menu")
    public CommonModel delMenu(@RequestBody List<Long> ids) {
        try {
            adminService.delMenus(cacheUtil.getAdminOperator(), ids);
            return CommonModel.Success(null);
        } catch (Exception e) {
            logger.error("{}删除菜单{}异常：", gson.toJson(cacheUtil.getAdminOperator()), gson.toJson(ids), e);
            return ExceptionUtil.GetCommonModel(e);
        }
    }

}
